local H = require "packages/hegemony/util"
local HM = require "packages/mod_hegemony/util"
local U = require "packages/utility/utility"
local extension = Package:new("heg_wende")
extension.extensionName = "mod_hegemony"
extension.game_modes_whitelist = { } -- 暂不开放

Fk:loadTranslationTable{
    ["heg_wende"] = "国战-文德武备",
    ["wd_heg"] = "文德武备",
}

local simayi = General(extension, "wd_heg__simayi", "jin", 3)
simayi:addCompanions("wd_heg__zhangchunhua")

simayi:addSkill("yingshis")
simayi:addSkill("xiongzhi")
simayi:addSkill("quanbian")
Fk:loadTranslationTable{
  ["wd_heg__simayi"] = "司马懿",
  ["#wd_heg__simayi"] = "通权达变",
  ["illustrator:wd_heg__simayi"] = "六道目",
  ["~wd_heg__simayi"] = "虎入骷冢，司马难兴。",
}

local zhangchunhua = General(extension, "wd_heg__zhangchunhua", "jin", 3, 3, General.Female)
local xuanmu = fk.CreateTriggerSkill{
  name = "wd_heg__xuanmu",
  mute = true,
  events = {fk.DamageInflicted},
  can_trigger = function (self, event, target, player, data)
    if target == player and player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 then
      return player.phase == Player.NotActive
    end
  end,
  on_use = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "@@wd_heg__xuanmu-turn", 1)
    player.room.logic:getCurrentEvent():findParent(GameEvent.Turn):addCleaner(function()
      player.room:handleAddLoseSkills(player, "-"..self.name)
    end)
  end,
}
local xuanmu_delay = fk.CreateTriggerSkill{
  name = "#wd_heg__xuanmu_delay",
  anim_type = "defensive",
  events = {fk.DamageInflicted},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:getMark("@@wd_heg__xuanmu-turn") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    player:broadcastSkillInvoke("wd_heg__xuanmu")
    return true
  end,
}
local huishi = fk.CreateTriggerSkill{
  name = "wd_heg__huishi",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw and #player.room.draw_pile % 10 > 1
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#wd_heg__huishi-invoke:::"..math.min(#player.room.draw_pile % 10, 6))
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local x = math.min(#room.draw_pile % 10, 6)
    if x == 0 then return true end
    local card_ids = room:getNCards(x)
    local y = x // 2
    local rusult = room:askForGuanxing(player, card_ids, {x-y, x}, {y, y}, self.name, true, {"Bottom", "toObtain"})
    for i = #rusult.top, 1, -1 do
      table.insert(room.draw_pile, rusult.top[i])
    end
    room:moveCardTo(rusult.bottom, Player.Hand, player, fk.ReasonPrey, self.name, "", false, player.id)
    return true
  end,
}
--xuanmu:addRelatedSkill(xuanmu_delay)
--zhangchunhua:addSkill(xuanmu)
zhangchunhua:addSkill(huishi)
zhangchunhua:addSkill("qingleng")
Fk:loadTranslationTable{
  ["wd_heg__zhangchunhua"] = "张春华",
  ["#wd_heg__zhangchunhua"] = "宣穆皇后",
  ["illustrator:wd_heg__zhangchunhua"] = "六道目",
  ["wd_heg__xuanmu"] = "宣穆",
  [":wd_heg__xuanmu"] = "当你于回合外受到伤害时，你可以防止之，然后本回合防止你受到的伤害并于本回合结束时失去此技能。",
  ["#wd_heg__xuanmu_delay"] = "宣穆",
  ["@@wd_heg__xuanmu-turn"] = "宣穆",
  ["wd_heg__huishi"] = "慧识",
  [":wd_heg__huishi"] = "摸牌阶段，你可以放弃摸牌，改为观看牌堆顶的X张牌，获得其中的一半（向下取整），然后将其余牌置入牌堆底。（X为牌堆数量的个位数且至多为6）",
  ["#wd_heg__huishi-invoke"] = "慧识：你可以放弃摸牌，改为观看牌堆顶%arg张牌并获得其中的一半，其余置于牌堆底",

  ["$wd_heg__xuanmu1"] = "四门穆穆，八面莹澈。",
  ["$wd_heg__xuanmu2"] = "天色澄穆，心明清静。",
  ["$wd_heg__huishi1"] = "你的想法，我已知晓。",
  ["$wd_heg__huishi2"] = "妾身慧眼，已看透太多。",
  ["~wd_heg__zhangchunhua"] = "冷眸残情，孤苦为一人。",
}

local simazhou = General(extension, "wd_heg__simazhou", "jin", 4)
local caiwang = fk.CreateViewAsSkill{
  name = "wd_heg__caiwang",
  anim_type = "control",
  pattern = "jink,nullification,slash",
  prompt = function()
    if Fk.currentResponsePattern == nil then
      return "#wd_heg__caiwang-slash"
    else
      if Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("jink")) and Self:getHandcardNum() == 1 then
        return "#wd_heg__caiwang-jink"
      elseif Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("nullification")) and #Self:getCardIds("e") == 1 then
        return "#wd_heg__caiwang-nullification"
      elseif Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("slash")) and #Self:getCardIds("j") == 1 then
        return "#wd_heg__caiwang-slash"
      end
    end
  end,
  interaction = function()
    local names = {}
    if Fk.currentResponsePattern == nil then
      local card = Fk:cloneCard("slash")
      if #Self:getCardIds("j") == 1 and Self:canUse(card) and not Self:prohibitUse(card) then
        table.insertIfNeed(names, "slash")
      end
    elseif Fk.currentResponsePattern then
      if Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("jink")) then  --FIXME：奇正相生
        if Self:getHandcardNum() == 1 then
          table.insertIfNeed(names, "jink")
        end
      end
      if Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("nullification")) then
        if #Self:getCardIds("e") == 1 then
          table.insertIfNeed(names, "nullification")
        end
      end
      if Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("slash")) then
        if #Self:getCardIds("j") == 1 then
          table.insertIfNeed(names, "slash")
        end
      end
    end
    if #names == 0 then return false end
    return UI.ComboBox { choices = names }
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    if self.interaction.data == "jink" then
      card:addSubcard(Self.player_cards[Player.Hand][1])
    elseif self.interaction.data == "nullification" then
      card:addSubcard(Self.player_cards[Player.Equip][1])
    elseif self.interaction.data == "slash" then
      card:addSubcard(Self.player_cards[Player.Judge][1])
    end
    if #card.subcards ~= 1 then return end
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return #player.player_cards[Player.Judge] == 1
  end,
  enabled_at_response = function(self, player, response)
    if Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):matchExp(self.pattern) then
      if Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("nullification")) then
        return #player.player_cards[Player.Equip] == 1
      elseif Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("jink")) then
        return player:getHandcardNum() == 1
      else
        return #player.player_cards[Player.Judge] == 1
      end
    end
  end,
}
simazhou:addSkill("caiwang")
simazhou:addSkill("naxiang")
Fk:loadTranslationTable{
  ["wd_heg__simazhou"] = "司马伷",
  ["#wd_heg__simazhou"] = "琅琊武王",
  ["illustrator:wd_heg__simazhou"] = "凝聚永恒",

  ["wd_heg__caiwang"] = "才望",
  [":wd_heg__caiwang"] = "你可以将最后一张手牌当【闪】使用或打出；将最后一张你装备区里的牌当【无懈可击】使用；将最后一张你判定区的牌当【杀】使用或打出。",
  ["#wd_heg__caiwang-discard"] = "才望：你可以弃置 %dest 一张牌",
  ["#wd_heg__caiwang-prey"] = "才望：你可以获得 %dest 一张牌",
  ["#wd_heg__caiwang-jink"] = "才望：你可以将最后一张手牌当【闪】使用或打出",
  ["#wd_heg__caiwang-nullification"] = "才望：你可以将最后一张装备当【无懈可击】使用",
  ["#wd_heg__caiwang-slash"] = "才望：你可以将最后一张判定区内的牌当【杀】使用或打出",

  ["$wd_heg__caiwang1"] = "才气不俗，声望四海。",
  ["$wd_heg__caiwang2"] = "绥怀之称，监守邺城。",
  ["~wd_heg__simazhou"] = "恩赐重物，病身难消受……",
}

local zhanghuyuechen = General(extension, "wd_heg__zhanghuyuechen", "jin", 4)
local xijue = fk.CreateTriggerSkill{
  name = "wd_heg__xijue",
  anim_type = "offensive",
  events = {fk.GeneralRevealed, fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self, true) then
      if event == fk.GeneralRevealed then
        for _, v in pairs(data) do
          if table.contains(Fk.generals[v]:getSkillNameList(), self.name) and player:getMark("wd_heg__xijue_used") == 0 then 
            self.cost_data = 4
            return true 
          end
        end
      else
        if target == player then
          local room = player.room
          local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
          if turn_event == nil then return false end
          local n = 0
          room.logic:getActualDamageEvents(1, function(e)
            local damage = e.data[1]
            if damage.from == player then
              n = n + damage.damage
            end
            return false
          end, nil, turn_event.id)
          if n > 0 then
            self.cost_data = n
            return true
          end
        end
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    if event == fk.GeneralRevealed then
      player.room:setPlayerMark(player, "wd_heg__xijue_used", 1)
    end
    player.room:addPlayerMark(player, "@wd_heg__zhanghuyuechen_jue", self.cost_data)
  end,

  refresh_events = {fk.EventLoseSkill},
  can_refresh = function(self, event, target, player, data)
    return player == target and data == self
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "@wd_heg__zhanghuyuechen_jue", 0)
  end,
}
local xijue_tuxi = fk.CreateTriggerSkill{
  name = "#wd_heg__xijue_tuxi",
  anim_type = "control",
  main_skill = xijue,
  events = {fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    return (target == player and player:hasSkill(xijue) and data.n > 0 and player:getMark("@wd_heg__zhanghuyuechen_jue") > 0 and
      not table.every(player.room:getOtherPlayers(player, false), function (p) return p:isKongcheng() end))
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room:getOtherPlayers(player, false), function(p)
      return not p:isKongcheng() end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, data.n, "#wd_heg__xijue_tuxi-invoke", "ex__tuxi", true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:removePlayerMark(player, "@wd_heg__zhanghuyuechen_jue", 1)
    player:broadcastSkillInvoke("ex__tuxi")
    local targets = table.simpleClone(self.cost_data)
    room:sortPlayersByAction(targets)
    for _, id in ipairs(targets) do
      if player.dead then break end
      local p = room:getPlayerById(id)
      if not (p.dead or p:isKongcheng()) then
        local c = room:askForCardChosen(player, p, "h", "ex__tuxi")
        room:obtainCard(player.id, c, false, fk.ReasonPrey)
      end
    end
    data.n = data.n - #targets
  end,
}
local xijue_xiaoguo = fk.CreateTriggerSkill{
  name = "#wd_heg__xijue_xiaoguo",
  anim_type = "offensive",
  main_skill = xijue,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target ~= player and not target.dead and player:hasSkill(xijue) and not player:isKongcheng() and
    player:getMark("@wd_heg__zhanghuyuechen_jue") > 0 and target.phase == Player.Finish
  end,
  on_cost = function(self, event, target, player, data)
    local card = player.room:askForDiscard(player, 1, 1, false, "wd_heg__xiaoguo", true, ".|.|.|.|.|basic", "#wd_heg__xijue_xiaoguo-invoke::"..target.id, true)
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:removePlayerMark(player, "@wd_heg__zhanghuyuechen_jue", 1)
    player:broadcastSkillInvoke("wd_heg__xiaoguo")
    room:doIndicate(player.id, {target.id})
    room:throwCard(self.cost_data, "wd_heg__xiaoguo", player, player)
    if target.dead then return false end
    if #room:askForDiscard(target, 1, 1, true, "wd_heg__xiaoguo", true, ".|.|.|.|.|equip", "#xiaoguo-discard:"..player.id) > 0 then
      player:drawCards(1, "wd_heg__xiaoguo")
    else
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = "wd_heg__xiaoguo",
      }
    end
  end,
}
xijue:addRelatedSkill(xijue_tuxi)
xijue:addRelatedSkill(xijue_xiaoguo)
zhanghuyuechen:addSkill(xijue)
zhanghuyuechen:addRelatedSkill("ex__tuxi")
zhanghuyuechen:addRelatedSkill("xiaoguo")
Fk:loadTranslationTable{
  ["wd_heg__zhanghuyuechen"] = "张虎乐綝",
  ["#wd_heg__zhanghuyuechen"] = "不辱门庭",
  ["designer:wd_heg__zhanghuyuechen"] = "张浩",
  ["illustrator:wd_heg__zhanghuyuechen"] = "凝聚永恒",

  ["wd_heg__xijue"] = "袭爵",
  [":wd_heg__xijue"] = "你首次明置此武将时，你获得4个“爵”标记；回合结束时，你获得X个“爵”标记（X为你本回合造成的伤害值）。你可以移去1个“爵”标记发动〖突袭〗或〖骁果〗。",
  ["@wd_heg__zhanghuyuechen_jue"] = "爵",
  ["#wd_heg__xijue_tuxi-invoke"] = "袭爵：你可以移去1个“爵”标记发动〖突袭〗",
  ["#wd_heg__xijue_xiaoguo-invoke"] = "袭爵：你可以移去1个“爵”标记对 %dest 发动〖骁果〗",
  ["#wd_heg__xijue_tuxi"] = "突袭",
  ["#wd_heg__xijue_xiaoguo"] = "骁果",

  ["$wd_heg__xijue1"] = "承爵于父，安能辱之！",
  ["$wd_heg__xijue2"] = "虎父安有犬子乎？",
  ["$ex__tuxi_wd_heg__zhanghuyuechen1"] = "动如霹雳，威震宵小！",
  ["$ex__tuxi_wd_heg__zhanghuyuechen2"] = "行略如风，摧枯拉朽！",
  ["$xiaoguo_wd_heg__zhanghuyuechen1"] = "大丈夫生于世，当沙场效忠！",
  ["$xiaoguo_wd_heg__zhanghuyuechen2"] = "骁勇善战，刚毅果断！",

  ["~wd_heg__zhanghuyuechen"] = "儿有辱……父亲威名……",
}

local xiahouhui = General(extension, "wd_heg__xiahouhui", "jin", 3, 3, General.Female)

xiahouhui:addSkill("yishi")
xiahouhui:addSkill("shidu")
Fk:loadTranslationTable{
  ["wd_heg__xiahouhui"] = "夏侯徽",
  ["#wd_heg__xiahouhui"] = "景怀皇后",
  ["illustrator:wd_heg__xiahouhui"] = "凝聚永恒",

  ["~wd_heg__xiahouhui"] = "夫君，你怎么对我如此狠心……",
}

local simashi = General(extension, "wd_heg__simashi", "jin", 3, 3)

simashi:addSkill("yimie")
simashi:addSkill("tairan")
simashi:addCompanions("wd_heg__yanghuiyu")
simashi:addCompanions("wd_heg__xiahouhui")
Fk:loadTranslationTable{
  ["wd_heg__simashi"] = "司马师",
  ["#wd_heg__simashi"] = "晋景王",
  ["illustrator:wd_heg__simashi"] = "拉布拉卡",

  ["~wd_heg__simashi"] = "子上，这是为兄给你打下的江山……",
}

local yanghuiyu = General(extension, "wd_heg__yanghuiyu", "jin", 3, 3, General.Female)
local huirong = fk.CreateTriggerSkill{
  name = "wd_heg__huirong",
  frequency = Skill.Compulsory,
  events = {fk.GeneralRevealed},
  anim_type = "control",
  can_trigger = function (self, event, target, player, data)
    if target == player and player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryGame) == 0 then
      for _, v in pairs(data) do
        if table.contains(Fk.generals[v]:getSkillNameList(), self.name) and player:getMark("wd_heg__xijue_used") == 0 then 
          self.cost_data = 4
          return true 
        end
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local tos = player.room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1, "#huirong-choose", self.name, false)
    if #tos > 0 then
      local to = room:getPlayerById(tos[1])
      local n = to:getHandcardNum() - to.hp
      if n > 0 then
        room:askForDiscard(to, n, n, false, self.name, false)
      else
        n = math.min(5-to:getHandcardNum(), -n)
        if n > 0 then
          to:drawCards(n, self.name)
        end
      end
    end
  end,
}
yanghuiyu:addSkill(huirong)
yanghuiyu:addSkill("ciwei")
yanghuiyu:addSkill("caiyuan")
Fk:loadTranslationTable{
  ["wd_heg__yanghuiyu"] = "羊徽瑜",
  ["#wd_heg__yanghuiyu"] = "景献皇后",
  ["illustrator:ol__yanghuiyu"] = "Jzeo",
  ["wd_heg__huirong"] = "慧容",
  [":wd_heg__huirong"] = "锁定技，你首次明置此武将时，令一名角色将手牌摸或弃至体力值（至多摸至五张）。",

  ["$wd_heg__huirong1"] = "红尘洗练，慧容不改。",
  ["$wd_heg__huirong2"] = "花貌易改，福惠长存。",
  ["~wd_heg__yanghuiyu"] = "韶华易老，佳容不再……",
}

local shibao = General(extension, "wd_heg__shibao", "jin", 4)
shibao:addSkill("zhuosheng")
Fk:loadTranslationTable{
  ["wd_heg__shibao"] = "石苞",
  ["#wd_heg__shibao"] = "乐陵郡公",
  ["illustrator:wd_heg__shibao"] = "凝聚永恒",

  ["~wd_heg__shibao"] = "寒门出身，难以擢升。",
}

local simazhao = General(extension, "wd_heg__simazhao", "jin", 3)
local zhaoran = fk.CreateTriggerSkill{
  name = "wd_heg__zhaoran",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#wd_heg__zhaoran-invoke")
  end,
  on_use = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "@wd_heg__zhaoran-phase", {})
    player:showCards(player:getCardIds("h"))
  end,
}
local zhaoran_trigger = fk.CreateTriggerSkill{
  name = "#wd_heg__zhaoran_trigger",
  mute = true,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:usedSkillTimes("wd_heg__zhaoran", Player.HistoryPhase) > 0 then
      for _, move in ipairs(data) do
        if move.from == player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand then
              if not table.find(player:getCardIds("h"), function(id)
                return Fk:getCardById(id).suit == Fk:getCardById(info.cardId).suit end) and
                not table.contains(player:getMark("@wd_heg__zhaoran-phase"), Fk:getCardById(info.cardId):getSuitString(true)) then
                return true
              end
            end
          end
        end
      end
    end
  end,
  on_trigger = function(self, event, target, player, data)
    local suits = {}
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand then
            if not table.find(player:getCardIds("h"), function(id)
              return Fk:getCardById(id).suit == Fk:getCardById(info.cardId).suit end) and
              not table.contains(player:getMark("@wd_heg__zhaoran-phase"), Fk:getCardById(info.cardId):getSuitString(true)) then
              table.insertIfNeed(suits, Fk:getCardById(info.cardId):getSuitString(true))
            end
          end
        end
      end
    end
    local mark = player:getMark("@wd_heg__zhaoran-phase")
    table.insertTableIfNeed(mark, suits)
    player.room:setPlayerMark(player, "@wd_heg__zhaoran-phase", mark)
    for i = 1, #suits, 1 do
      self:doCost(event, target, player, suits)
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, "wd_heg__zhaoran", "drawcard")
    player:drawCards(1, "wd_heg__zhaoran")
  end,
}
zhaoran:addRelatedSkill(zhaoran_trigger)
simazhao:addSkill("choufa")
simazhao:addSkill(zhaoran)
simazhao:addCompanions("wd_heg__wangyuanji")
simazhao:addCompanions("wd_heg__shibao")
Fk:loadTranslationTable{
  ["wd_heg__simazhao"] = "司马昭",
  ["#wd_heg__simazhao"] = "晋文帝",
  ["illustrator:wd_heg__simazhao"] = "君桓文化",

  ["wd_heg__zhaoran"] = "昭然",
  --[":wd_heg__zhaoran"] = "出牌阶段开始时，你可令你的手牌对所有角色可见直到此阶段结束。若如此做，当你于本阶段失去任意花色的最后一张手牌时（每种花色限一次），"..
  [":wd_heg__zhaoran"] = "出牌阶段开始时，你可展示所有手牌。若如此做，当你于本阶段失去任意花色的最后一张手牌时（每种花色限一次），"..
  "你摸一张牌。",
  ["#wd_heg__zhaoran-invoke"] = "昭然：你可以展示所有手牌，本阶段你失去一种花色最后的手牌后摸一张牌",
  ["@wd_heg__zhaoran-phase"] = "昭然",
  ["#wd_heg__zhaoran_trigger"] = "昭然",

  ["$wd_heg__zhaoran1"] = "行昭然于世，赦众贼以威。",
  ["$wd_heg__zhaoran2"] = "吾之心思，路人皆知。",
  ["~wd_heg__simazhao"] = "司马三代，一梦成空……",
}

local xuangongzhu = General(extension, "wd_heg__xuangongzhu", "jin", 3, 3, General.Female)
xuangongzhu:addSkill("qimei")
xuangongzhu:addSkill("zhuijix")
xuangongzhu:addCompanions("wd_heg__duyu")
Fk:loadTranslationTable{
  ["wd_heg__xuangongzhu"] = "宣公主",
  ["#wd_heg__xuangongzhu"] = "高陵公主",
  ["designer:wd_heg__xuangongzhu"] = "世外高v狼",
  ["illustrator:wd_heg__xuangongzhu"] = "凡果",

  ["~wd_heg__xuangongzhu"] = "元凯，我去也……",
}

local wangyuanji = General(extension, "wd_heg__wangyuanji", "jin", 3, 3, General.Female)
wangyuanji:addSkill("yanxi")
Fk:loadTranslationTable{
  ["wd_heg__wangyuanji"] = "王元姬",
  ["#wd_heg__wangyuanji"] = "文明皇后",
  ["illustrator:wd_heg__wangyuanji"] = "六道目",

  ["~wd_heg__wangyuanji"] = "祖父已逝，哀凄悲戚。",
}

local duyu = General(extension, "wd_heg__duyu", "jin", 4)
duyu:addSkill("sanchen")
Fk:loadTranslationTable{
  ["wd_heg__duyu"] = "杜预",
  ["#wd_heg__duyu"] = "文成武德",
  ["designer:wd_heg__duyu"] = "张浩",
  ["illustrator:wd_heg__duyu"] = "君桓文化",

  ["~wd_heg__duyu"] = "金瓯尚缺，死难瞑目……",
}

local weiguan = General(extension, "wd_heg__weiguan", "jin", 4)
local zhongyun = fk.CreateTriggerSkill{
  name = "wd_heg__zhongyun",
  anim_type = "control",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player.hp == player:getHandcardNum() and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 then
      for _, move in ipairs(data) do
        if move.to == player.id and move.toArea == Card.PlayerHand then
          return true
        end
        for _, info in ipairs(move.moveInfo) do
          if move.from == player.id and info.fromArea == Card.PlayerHand then
            return true
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room:getOtherPlayers(player), function (p) return not p:isNude() end)
    if #targets > 0 then
      local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#wd_heg__zhongyun-discard", self.name, true)
      if #to > 0 then
        local id = room:askForCardChosen(player, room:getPlayerById(to[1]), "he", self.name)
        room:throwCard({id}, self.name, room:getPlayerById(to[1]), player)
        return
      end
    end
    player:drawCards(1, self.name)
  end,
}
weiguan:addSkill(zhongyun)
weiguan:addSkill("shenpin")
Fk:loadTranslationTable{
  ["wd_heg__weiguan"] = "卫瓘",
  ["#wd_heg__weiguan"] = "兰陵郡公",
  ["illustrator:wd_heg__weiguan"] = "Karneval",
  ["wd_heg__zhongyun"] = "忠允",
  [":wd_heg__zhongyun"] = "锁定技，每回合限一次，当你获得或失去手牌后，若你的体力值与你的手牌数相等，你摸一张牌或弃置一名其他角色的一张牌。",
  ["#wd_heg__zhongyun-discard"] = "忠允：弃置一名其他角色的一张牌，或点“取消”摸一张牌",

  ["$wd_heg__zhongyun1"] = "秉公行事，无所亲疏。",
  ["$wd_heg__zhongyun2"] = "明晰法理，通晓人情。",
  ["~wd_heg__weiguan"] = "辞荣善终，不可求……",
}

local zhongyan = General(extension, "wd_heg__zhongyan", "jin", 3, 3, General.Female)
local bolan_skills = {
  "quhu", "qiangxi", "qice", "daoshu", "tiaoxin", "qiangwu", "tianyi", "hs__zhiheng", "ex__jieyin", "ex__guose",
  "lijian", "qingnang", "ganlu", "mingce", "mizhao", "sanchen", "gongxin", "ex__chuli",
  --相较OL删去了离魂，增加了甘露，同时将制衡换成国战使用版本，将挑衅换成标姜维挑衅
}
---@param room Room
local getBolanSkills = function(room)
  local mark = room:getTag("BolanSkills")
  if mark then
    return mark
  else
    --[[local all_skills = {}
    for _, g in ipairs(room.general_pile) do
      for _, s in ipairs(Fk.generals[g]:getSkillNameList()) do
        table.insert(all_skills, s)
      end
    end
    local skills = table.filter(bolan_skills, function(s) return table.contains(all_skills, s) end)]]
    room:setTag("BolanSkills", bolan_skills)
    return bolan_skills
  end
end
local bolan = fk.CreateTriggerSkill{
  name = "wd_heg__bolan",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local skills = table.filter(getBolanSkills(room), function (skill_name)
      return not player:hasSkill(skill_name, true)
    end)
    if #skills > 0 then
      local choice = room:askForChoice(player, table.random(skills, 3), self.name, "#wd_heg__bolan-choice::"..player.id, true)
      room:handleAddLoseSkills(player, choice)
      room.logic:getCurrentEvent():findParent(GameEvent.Phase):addCleaner(function()
        room:handleAddLoseSkills(player, "-"..choice)
      end)
    end
  end,

  refresh_events = {fk.GameStart, fk.EventAcquireSkill, fk.EventLoseSkill, fk.Deathed},
  can_refresh = function(self, event, target, player, data)
    if event == fk.GameStart then
      return player:hasSkill(self, true)
    elseif event == fk.EventAcquireSkill or event == fk.EventLoseSkill then
      return target == player and data == self and
        not table.find(player.room:getOtherPlayers(player), function(p) return p:hasSkill(self, true) end)
    else
      return target == player and player:hasSkill(self, true, true) and
        not table.find(player.room:getOtherPlayers(player), function(p) return p:hasSkill(self, true) end)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart or event == fk.EventAcquireSkill then
      for _, p in ipairs(room:getOtherPlayers(player)) do
        room:handleAddLoseSkills(p, "wd_heg__bolan&", nil, false, true)
      end
    else
      for _, p in ipairs(room:getOtherPlayers(player, true, true)) do
        room:handleAddLoseSkills(p, "-wd_heg__bolan&", nil, false, true)
      end
    end
  end,
}
local bolan_active = fk.CreateActiveSkill{
  name = "wd_heg__bolan&",
  anim_type = "special",
  card_num = 0,
  target_num = 0,
  prompt = "#wd_heg__bolan-other",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = table.find(room:getOtherPlayers(player), function(p)
      return p:hasSkill(bolan, true)
    end)
    if not target then return end
    target:broadcastSkillInvoke("wd_heg__bolan")
    room:doIndicate(player.id, {target.id})
    room:loseHp(player, 1, "wd_heg__bolan")
    if player.dead or target.dead then return end
    local skills = table.filter(getBolanSkills(room), function (skill_name)
      return not player:hasSkill(skill_name, true)
    end)
    if #skills > 0 then
      local choice = room:askForChoice(target, table.random(skills, 3), self.name, "#wd_heg__bolan-choice::"..player.id, true)
      room:handleAddLoseSkills(player, choice, nil)
      room.logic:getCurrentEvent():findParent(GameEvent.Phase):addCleaner(function()
        room:handleAddLoseSkills(player, "-"..choice)
      end)
    end
  end,
}
Fk:addSkill(bolan_active)
zhongyan:addSkill(bolan)
zhongyan:addSkill("yifa")
Fk:loadTranslationTable{
  ["wd_heg__zhongyan"] = "钟琰",
  ["#wd_heg__zhongyan"] = "聪慧弘雅",
  ["illustrator:wd_heg__zhongyan"] = "明暗交界",
  ["wd_heg__bolan"] = "博览",
  [":wd_heg__bolan"] = "出牌阶段开始时，你可以从随机三个“出牌阶段限一次”的技能中选择一个获得直到本阶段结束；其他角色的出牌阶段限一次，其可以失去1点体力，令你从随机三个“出牌阶段限一次”的技能中选择一个，其获得之直到此阶段结束。"..
  "<br><font color='gray'><small>技能池（未标明即为标准版技能）：<br>挑衅、青囊、离间、驱虎、天义、强袭、攻心、甘露、枪舞、密诏、明策、除疬、奇策、三陈、盗书、国色（界）、结姻（界）、制衡（国战）</small></font>",

  ["wd_heg__bolan&"] = "博览",
  [":wd_heg__bolan&"] = "出牌阶段限一次，你可以失去1点体力，令钟琰从随机三个“出牌阶段限一次”的技能中选择一个，你获得之直到此阶段结束。",
  ["#wd_heg__bolan-choice"] = "博览：选择令 %dest 此阶段获得技能",
  ["#wd_heg__bolan-other"] = "博览：你可失去1点体力，令钟琰从三个“出牌阶段限一次”的技能中选择一个令你获得",

  ["$wd_heg__bolan1"] = "博览群书，融会贯通。",
  ["$wd_heg__bolan2"] = "博览于文，约之以礼。",
  ["~wd_heg__zhongyan"] = "嗟尔姜任，邈我不留。",
}

local xinchang = General(extension, "wd_heg__xinchang", "jin", 3)
xinchang:addSkill("canmou")
xinchang:addSkill("congjianx")
Fk:loadTranslationTable{
  ["wd_heg__xinchang"] = "辛敞",
  ["#wd_heg__xinchang"] = "英鉴中铭",
  ["illustrator:wd_heg__xinchang"] = "君桓文化",


  ["~wd_heg__xinchang"] = "宪英，救我！",
}

local jiachong = General(extension, "wd_heg__jiachong", "jin", 3)
local xiongshu = fk.CreateTriggerSkill{
  name = "wd_heg__xiongshu",
  anim_type = "special",
  events = {fk.PreDamage},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and data.to ~= player and not player:isKongcheng()
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if player == target then
      local to, card = room:askForChooseCardAndPlayers(player, table.map(room:getOtherPlayers(player), Util.IdMapper), 1, 1, ".|.|.|hand", "#wd_heg__xiongshu-choose", self.name)
      if #to > 0 then
        self.cost_data = {to = to, card = card}
        return true
      end
    else
      local card = room:askForCard(player, 1, 1, false, self.name, true, ".", "#wd_heg__xiongshu-card")
      self.cost_data = {card = card}
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data.card, self.name, player, player)
    if player == target then
      local to = room:getPlayerById(self.cost_data.to[1])
      data.from = to
    else
      data.from = player
    end
  end,
}
jiachong:addSkill(xiongshu)
jiachong:addSkill("jianhui")
jiachong:addCompanions("wd_heg__simazhao")
Fk:loadTranslationTable{
  ["wd_heg__jiachong"] = "贾充",
  ["#wd_heg__jiachong"] = "鲁郡公",
  ["illustrator:wd_heg__jiachong"] = "游漫美绘",
  ["wd_heg__xiongshu"] = "凶竖",
  [":wd_heg__xiongshu"] = "每回合限一次，当你/其他角色即将造成伤害时，若受伤角色不为你，你可以弃置一张手牌，令一名其他角色/你成为此伤害来源。",
  ["#wd_heg__xiongshu-choose"] = "凶竖：你可以弃置一张手牌，令一名其他角色成为此伤害来源",
  ["#wd_heg__xiongshu-card"] = "凶竖：你可以弃置一张手牌，然后成为此伤害来源",

  ["$wd_heg__xiongshu1"] = "怀志拥权，谁敢不服？",
  ["$wd_heg__xiongshu2"] = "天下凶凶，由我一人。",
  ["~wd_heg__jiachong"] = "任元褒，吾与汝势不两立！",
}

local yangyan = General(extension, "wd_heg__yangyan", "jin", 3, 3, General.Female)
local xuanbei = fk.CreateActiveSkill{
  name = "wd_heg__xuanbei",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#wd_heg__xuanbei",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and not Fk:currentRoom():getPlayerById(to_select):isAllNude()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local id = room:askForCardChosen(player, target, "hej", self.name)
    local card = Fk:cloneCard("slash")
    card:addSubcard(id)
    if U.canUseCardTo(room, target, player, card, false, false) then
      local use = {
        from = target.id,
        tos = {{player.id}},
        card = card,
        skillName = self.name,
        extraUse = true,
      }
      room:useCard(use)
    end
  end,
}
local xianwan = fk.CreateViewAsSkill{
  name = "wd_heg__xianwan",
  pattern = "slash,jink",
  anim_type = "defensive",
  prompt = function()
    if Self.chained then
      return "#wd_heg__xianwan-slash"
    else
      return "#wd_heg__xianwan-jink"
    end
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    local card
    if Self:hasSkill(self) then
      if Self.chained then
        card = Fk:cloneCard("slash")
      else
        card = Fk:cloneCard("jink")
      end
    end
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    if player.chained then
      player:setChainState(false)
    else
      player:setChainState(true)
    end
  end,
  enabled_at_response = function(self, player, response)
    return not response
  end,
}
yangyan:addSkill(xuanbei)
yangyan:addSkill(xianwan)
yangyan:addCompanions("wd_heg__yangzhi")
Fk:loadTranslationTable{
  ["wd_heg__yangyan"] = "杨艳",
  ["#wd_heg__yangyan"] = "武元皇后",
  ["illustrator:wd_heg__yangyan"] = "游漫美绘",
  ["wd_heg__xuanbei"] = "选备",
  [":wd_heg__xuanbei"] = "出牌阶段限一次，你可以选择一名其他角色区域内的一张牌，令其将此牌当无距离限制的【杀】对你使用。",
  ["#wd_heg__xuanbei"] = "选备：选择一名角色，将其区域内一张牌当【杀】对你使用",
  ["wd_heg__xianwan"] = "娴婉",
  [":wd_heg__xianwan"] = "每回合限一次，你可以横置，视为使用一张【闪】；你可以重置，视为使用一张【杀】。",
  ["#wd_heg__xianwan-slash"] = "娴婉：你可以重置，视为使用一张【杀】",
  ["#wd_heg__xianwan-jink"] = "娴婉：你可以横置，视为使用一张【闪】",

  ["$wd_heg__xuanbei1"] = "博选良家，以充后宫。",
  ["$wd_heg__xuanbei2"] = "非良家，不可选也。",
  ["$wd_heg__xianwan1"] = "婉而从物，不竞不争。",
  ["$wd_heg__xianwan2"] = "娴婉恭谨，重贤加礼。",
  ["~wd_heg__yangyan"] = "一旦殂损，痛悼伤怀……",
}

local yangzhi = General(extension, "wd_heg__yangzhi", "jin", 3, 3, General.Female)
local wanyi_select = fk.CreateActiveSkill{
  name = "wd_heg__wanyi_select",
  card_num = 1,
  target_num = 1,
  expand_pile = "wd_heg__wanyi",
  target_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Self:getPileNameOfId(to_select) == "wd_heg__wanyi"
  end,
}
Fk:addSkill(wanyi_select)
local wanyi = fk.CreateTriggerSkill{
  name = "wd_heg__wanyi",
  anim_type = "control",
  derived_piles = "wd_heg__wanyi",
  events = {fk.TargetSpecified, fk.EventPhaseStart, fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.TargetSpecified then
        if (data.card.trueName ~= "slash" and not data.card:isCommonTrick()) or data.to == player.id then return false end
        local to = player.room:getPlayerById(data.to) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
        return U.isOnlyTarget(to, data, event) and not to:isNude()
      elseif #player:getPile("wd_heg__wanyi") > 0 then
        if event == fk.EventPhaseStart then
          return player.phase == Player.Finish
        else
          return true
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.TargetSpecified then
      local room = player.room
      if room:askForSkillInvoke(player, self.name, nil, "#wd_heg__wanyi-invoke::"..data.to) then
        room:doIndicate(player.id, {data.to})
        return true
      end
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetSpecified then
      local id = room:askForCardChosen(player, room:getPlayerById(data.to), "he", self.name)
      player:addToPile(self.name, id, true, self.name)
    else
      local _, dat = room:askForUseActiveSkill(player, "wd_heg__wanyi_select", "#wd_heg__wanyi-card", false, Util.DummyTable, true)
      if dat then
        room:moveCardTo(dat.cards, Card.PlayerHand, room:getPlayerById(dat.targets[1]), fk.ReasonGive, self.name, nil, true, player.id)
      else
        room:moveCardTo(player:getPile("wd_heg__wanyi")[1], Card.PlayerHand, player, fk.ReasonGive, self.name, nil, true, player.id)
      end
    end
  end,
}

local wanyi_prohibit = fk.CreateProhibitSkill{
  name = "#wd_heg__wanyi_prohibit",
  prohibit_use = function(self, player, card)
    return table.find(player:getPile("wd_heg__wanyi"), function(id) return Fk:getCardById(id).color == card.color end)
  end,
  prohibit_response = function(self, player, card)
    return table.find(player:getPile("wd_heg__wanyi"), function(id) return Fk:getCardById(id).color == card.color end)
  end,
  prohibit_discard = function(self, player, card)
    return table.find(player:getPile("wd_heg__wanyi"), function(id) return Fk:getCardById(id).color == card.color end)
  end,
}
local maihuo = fk.CreateTriggerSkill{
  name = "wd_heg__maihuo",
  anim_type = "defensive",
  derived_piles = "yangzhi_huo",
  events = {fk.TargetConfirmed, fk.Damage},
  can_trigger = function(self, event, target, player, data)
    if player ~= target or not player:hasSkill(self) then return false end
    if data.card.trueName == "slash" and U.isOnlyTarget(player, data, event) and U.isPureCard(data.card) and data.from then
      if (data.extra_data and data.extra_data.wd_heg__maihuo) then return false end
      local from = player.room:getPlayerById(data.from)
      return from ~= nil and not from.dead and #from:getPile("yangzhi_huo") == 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if room:askForSkillInvoke(player, self.name, nil, "#wd_heg__maihuo-invoke::"..data.from..":"..data.card:toLogString()) then
      room:doIndicate(player.id, {data.from})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    table.insertIfNeed(data.nullifiedTargets, player.id)
    if room:getCardArea(data.card) == Card.Processing then
      room:doIndicate(player.id, {data.from})
      local to = room:getPlayerById(data.from)
      to:addToPile("yangzhi_huo", data.card, true, self.name)
      room:setPlayerMark(to, self.name, {player.id, data.card.id})
    end
  end,
}
local maihuo_delay = fk.CreateTriggerSkill{
  name = "#wd_heg__maihuo_delay",
  mute = true,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player == target and player.phase == Player.Play and #player:getPile("yangzhi_huo") > 0 and not player.dead
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(player:getMark("wd_heg__maihuo")[1])
    local card = Fk:getCardById(player:getPile("yangzhi_huo")[1])
    to:broadcastSkillInvoke("wd_heg__maihuo")
    room:notifySkillInvoked(to, self.name, "control")
    room:setPlayerMark(player, "wd_heg__maihuo", 0)
    if U.canUseCardTo(room, player, to, card, true, true) then
      room:useCard({
        from = player.id,
        tos = {{to.id}},
        card = card,
        extraUse = false,
        extra_data = {wd_heg__maihuo = true},
      })
    else
      room:moveCards({
        from = player.id,
        ids = player:getPile("yangzhi_huo"),
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonPutIntoDiscardPile,
        skillName = "wd_heg__maihuo",
      })
    end
  end,
}
wanyi:addRelatedSkill(wanyi_prohibit)
maihuo:addRelatedSkill(maihuo_delay)
yangzhi:addSkill(wanyi)
yangzhi:addSkill(maihuo)
Fk:loadTranslationTable{
  ["wd_heg__yangzhi"] = "杨芷",
  ["#wd_heg__yangzhi"] = "武悼皇后",
  ["illustrator:wd_heg__yangzhi"] = "游漫美绘",
  ["wd_heg__wanyi"] = "婉嫕",
  [":wd_heg__wanyi"] = "每回合限一次，当你使用【杀】或普通锦囊牌指定唯一其他角色为目标后，你可以将其一张牌置于你的武将牌上。"..
  "你不能使用、打出、弃置与“婉嫕”牌颜色相同的牌。结束阶段或当你受到伤害后，你令一名角色获得一张“婉嫕”牌。",
  ["#wd_heg__wanyi-invoke"] = "婉嫕：你可以将 %dest 的一张牌置于你的武将牌上",
  ["wd_heg__wanyi_select"] = "婉嫕",
  ["#wd_heg__wanyi-card"] = "婉嫕：令一名角色获得一张“婉嫕”牌",
  ["wd_heg__maihuo"] = "埋祸",
  [":wd_heg__maihuo"] = "其他角色非因本技能使用的非转化的【杀】指定你为唯一目标后，若其没有“祸”，你可以令此【杀】对你无效并将之置于其武将牌上，称为“祸”，"..
  "其下个出牌阶段开始时对你使用此【杀】（须合法且有次数限制，不合法则移去之）。",
  ["#wd_heg__maihuo-invoke"] = "埋祸：你可以令 %dest 对你使用的%arg无效并将之置为其“祸”，延迟到其下个出牌阶段对你使用",
  ["#wd_heg__maihuo_delay"] = "埋祸",

  ["$wd_heg__wanyi1"] = "天性婉嫕，易以道御。",
  ["$wd_heg__wanyi2"] = "婉嫕利珍，为后攸行。",
  ["$wd_heg__maihuo1"] = "祸根未决，转而滋蔓。",
  ["$wd_heg__maihuo2"] = "无德之亲，终为祸根。",
  ["~wd_heg__yangzhi"] = "贾氏……构陷……",
}

local zuofen = General(extension, "wd_heg__zuofen", "jin", 3, 3, General.Female)
local zhaosong = fk.CreateTriggerSkill{
  name = "wd_heg__zhaosong",
  anim_type = "control",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and target.phase == Player.Draw and not target:isKongcheng() and
      target:getMark("@@zuofen_lei") == 0 and target:getMark("@@zuofen_fu") == 0 and target:getMark("@@zuofen_song") == 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local basic = "basic"
    local trick = "trick"
    local equip = "equip"
    for _, p in ipairs(room.alive_players) do
      if p:getMark("@@zuofen_song") ~= 0 then
        basic = ""
      end
      if p:getMark("@@zuofen_lei") ~= 0 then
        trick = ""
      end
      if p:getMark("@@zuofen_fu") ~= 0 then
        equip = ""
      end
    end
    if #basic + #trick + #equip > 3 then
      local tab = {}
      for _, i in ipairs({basic, trick, equip}) do
        if #i > 1 then
          table.insert(tab, i)
        end
      end
      if #tab > 1 then
        self.cost_data = ".|.|.|.|.|" .. table.concat(tab, ",")
      elseif #tab == 1 then
        self.cost_data = ".|.|.|.|.|" .. tab[1]
      end
      return player.room:askForSkillInvoke(player, self.name, nil, "#wd_heg__zhaosong-invoke::"..target.id)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, {target.id})
    local ids = room:askForCard(target, 1, 1, false, self.name, true, self.cost_data, "#wd_heg__zhaosong-give:"..player.id)
    if #ids > 0 then
      local card = Fk:getCardById(ids[1])
      room:obtainCard(player.id, ids[1], false, fk.ReasonGive)
      if target.dead then return false end
      local mark
      if card.type == Card.TypeTrick then
        mark = "@@zuofen_lei"
      elseif card.type == Card.TypeEquip then
        mark = "@@zuofen_fu"
      elseif card.type == Card.TypeBasic then
        mark = "@@zuofen_song"
      end
      room:addPlayerMark(target, mark, 1)
    end
  end,
}
local zhaosong_trigger = fk.CreateTriggerSkill{
  name = "#wd_heg__zhaosong_trigger",
  mute = true,
  events = {fk.EnterDying, fk.EventPhaseStart, fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    if target == player then
      if event == fk.EnterDying then
        return player:getMark("@@zuofen_lei") > 0
      elseif event == fk.EventPhaseStart then
        return player:getMark("@@zuofen_fu") > 0 and player.phase == Player.Play and
          not table.every(player.room:getAlivePlayers(), function(p) return p:isAllNude() end)
      else
        return player:getMark("@@zuofen_song") > 0 and data.card.trueName == "slash" and #data.tos == 1 and
        #player.room:getUseExtraTargets(data) > 0 
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EnterDying then
      return room:askForSkillInvoke(player, self.name, nil, "#wd_heg__zhaosong1-invoke")
    elseif event == fk.EventPhaseStart then
      local to = room:askForChoosePlayers(player, table.map(table.filter(room:getAlivePlayers(), function(p)
        return not p:isAllNude() end), Util.IdMapper), 1, 1, "#wd_heg__zhaosong2-invoke", self.name, true)
      if #to > 0 then
        self.cost_data = to[1]
        return true
      end
    else
      local tos = room:askForChoosePlayers(player, player.room:getUseExtraTargets(data),
      1, 2, "#wd_heg__zhaosong3-invoke", self.name, true)
      if #tos > 0 then
        self.cost_data = tos
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EnterDying then
      room:notifySkillInvoked(player, self.name, "support")
      room:removePlayerMark(player, "@@zuofen_lei", 1)
      room:recover({
        who = player,
        num = 1 - player.hp,
        recoverBy = player,
        skillName = self.name
      })
      if not player.dead then
        player:drawCards(1, self.name)
      end
    elseif event == fk.EventPhaseStart then
      room:notifySkillInvoked(player, self.name, "control")
      room:removePlayerMark(player, "@@zuofen_fu", 1)
      local to = room:getPlayerById(self.cost_data)
      local cards = room:askForCardsChosen(player, to, 1, 2, "hej", self.name)
      room:throwCard(cards, self.name, to, player)
    else
      room:notifySkillInvoked(player, self.name, "offensive")
      room:removePlayerMark(player, "@@zuofen_song", 1)
      for _, id in ipairs(self.cost_data) do
        TargetGroup:pushTargets(data.tos, id)
      end
    end
  end,
}
zhaosong:addRelatedSkill(zhaosong_trigger)
zuofen:addSkill(zhaosong)
zuofen:addSkill("lisi")
Fk:loadTranslationTable{
  ["wd_heg__zuofen"] = "左棻",
  ["#wd_heg__zuofen"] = "无宠的才女",
  ["illustrator:wd_heg__zuofen"] = "明暗交界",
  ["wd_heg__zhaosong"] = "诏颂",
  [":wd_heg__zhaosong"] = "一名其他角色于其摸牌阶段结束时，若其没有标记，你可令其选择是否交给你一张手牌（正面向上），然后根据此牌的类型，令该角色获得对应的标记（每种标记场上限一个）："..
  "锦囊牌，“诔”标记；装备牌，“赋”标记；基本牌，“颂”标记。拥有标记的角色：<br>"..
  "进入濒死状态时，可弃置“诔”，回复体力至1点，摸一张牌；<br>"..
  "出牌阶段开始时，可弃置“赋”，弃置一名角色区域内的至多两张牌；<br>"..
  "使用【杀】仅指定一个目标时，可弃置“颂”，为此【杀】额外选择至多两个目标。",
  ["@@zuofen_lei"] = "诔",
  ["@@zuofen_fu"] = "赋",
  ["@@zuofen_song"] = "颂",
  ["#wd_heg__zhaosong-invoke"] = "诏颂：你可以对 %dest 发动“诏颂”",
  ["#wd_heg__zhaosong-give"] = "诏颂：交给 %src 一张手牌，根据类别你获得效果<br>"..
  "锦囊-进入濒死状态回复体力并摸牌；装备-弃置一名角色两张牌；基本-使用【杀】可额外指定两个目标",
  ["#wd_heg__zhaosong_trigger"] = "诏颂",
  ["#wd_heg__zhaosong1-invoke"] = "诏颂：你可以弃置“诔”，回复体力至1点并摸一张牌",
  ["#wd_heg__zhaosong2-invoke"] = "诏颂：你可以弃置“赋”，弃置一名角色区域内至多两张牌",
  ["#wd_heg__zhaosong3-invoke"] = "诏颂：你可以弃置“颂”，额外选择至多两个目标",

  ["$wd_heg__zhaosong1"] = "领诏者，可上而颂之。",
  ["$wd_heg__zhaosong2"] = "今为诏，以上告下也。",
  ["~wd_heg__zuofen"] = "惨怆愁悲……",
}

local yanghu = General(extension, "wd_heg__yanghu", "jin", 3)
yanghu:addSkill("chongxin")
yanghu:addSkill("weishu")
Fk:loadTranslationTable{
  ["wd_heg__yanghu"] = "羊祜",
  ["#wd_heg__yanghu"] = "执德清劭",
  ["illustrator:wd_heg__yanghu"] = "匠人绘",

  ["~wd_heg__yanghu"] = "当断不断，反受其乱……",
}

local zhanghua = General(extension, "wd_heg__zhanghua", "jin", 3)
local jianhe = fk.CreateActiveSkill{
  name = "wd_heg__jianhe",
  anim_type = "offensive",
  --relate_to_place = 'm',
  prompt = "#wd_heg__jianhe-active",
  min_card_num = 2,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, to_select, selected)
    if #selected == 0 then
      return true
    else
      if Fk:getCardById(selected[1]).type == Card.TypeEquip then
        return Fk:getCardById(to_select).type == Card.TypeEquip
      end
      return Fk:getCardById(to_select).trueName == Fk:getCardById(selected[1]).trueName
    end
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:currentRoom():getPlayerById(to_select):getMark("wd_heg__jianhe-turn") == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:setPlayerMark(target, "wd_heg__jianhe-turn", 1)
    local n = #effect.cards
    room:recastCard(effect.cards, player, self.name)
    if #target:getCardIds("he") >= n then
      local type_name = Fk:getCardById(effect.cards[1]):getTypeString()
      local cards = room:askForCard(target, n, n, true, self.name, true,
      ".|.|.|.|.|"..type_name, "#wd_heg__jianhe-choose:::"..n..":"..type_name)
      if #cards > 0 then
        room:recastCard(cards, target, self.name)
        return
      end
    end
    room:damage{
      from = player,
      to = target,
      damage = 1,
      damageType = fk.ThunderDamage,
      skillName = self.name,
    }
  end
}
Fk:addSkill(jianhe)
zhanghua:addSkill("bihun")
zhanghua:addSkill("wd_heg__jianhe")
zhanghua:addSkill("chuanwu")
Fk:loadTranslationTable{
  ["wd_heg__zhanghua"] = "张华",
  ["#wd_heg__zhanghua"] = "双剑化龙",
  ["designer:wd_heg__zhanghua"] = "玄蝶既白",
  ["illustrator:wd_heg__zhanghua"] = "匠人绘",
  ["cv:wd_heg__zhanghua"] = "苏至豪",

  ["wd_heg__jianhe"] = "剑合",
  [":wd_heg__jianhe"] = "出牌阶段限一次，你可以重铸至少两张同名牌或至少两张装备牌，令一名角色选择一项：1.重铸等量张与之类型相同的牌；2.受到你造成的1点雷电伤害。",
  ["#wd_heg__jianhe-active"] = "发动 剑合，选择至少两张同名牌重铸，并选择一名角色",
  ["#wd_heg__jianhe-choose"] = "剑合：你需重铸%arg张%arg2，否则受到1点雷电伤害",

  ["$wd_heg__jianhe_wd_heg__zhanghua1"] = "身临朝阙，腰悬太阿。",
  ["$wd_heg__jianhe_wd_heg__zhanghua2"] = "位登三事，当配龙泉。",
  ["~wd_heg__zhanghua"] = "桑化为柏，此非不祥乎？",
}

local wangxiang = General(extension, "wd_heg__wangxiang", "jin", 3)
wangxiang:addSkill("bingxin")
Fk:loadTranslationTable{
  ["wd_heg__wangxiang"] = "王祥",
  ["#wd_heg__wangxiang"] = "沂川跃鲤",
  ["illustrator:wd_heg__wangxiang"] = "KY",

  ["~wd_heg__wangxiang"] = "夫生之有死，自然之理也。",
}

local wangyan = General(extension, "wd_heg__wangyan", "jin", 3)
--wangyan:addSkill("yangkuang")
wangyan:addSkill("cihuang")
wangyan:addSkill("sanku")
Fk:loadTranslationTable{
  ["wd_heg__wangyan"] = "王衍",
  ["#wd_heg__wangyan"] = "玄虚陆沉",
  ["designer:wd_heg__wangyan"] = "玄蝶既白",
  ["illustrator:wd_heg__wangyan"] = "匠人绘",

  ["~wd_heg__wangyan"] = "影摇枭鸱动，三窟难得生。",
}


local chengjichengcui = General(extension, "wd_heg__chengjichengcui", "jin", 5)
chengjichengcui:addSkill("tousui")
chengjichengcui:addSkill("chuming")
Fk:loadTranslationTable{
  ["wd_heg__chengjichengcui"] = "成济成倅",
  ["#wd_heg__chengjichengcui"] = "袒忿半瓦",
  ["designer:wd_heg__chengjichengcui"] = "玄蝶既白",
  ["illustrator:wd_heg__chengjichengcui"] = "君桓文化",

  ["~wd_heg__chengjichengcui"] = "今为贼子贾充所害！",
}



local simayan = General(extension, "wd_heg__simayan", "jin", 3)
local juqi = fk.CreateTriggerSkill{
  name = "wd_heg__juqi",
  switch_skill_name = "wd_heg__juqi",
  mute = true,
  anim_type = "switch",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if player == target and player:hasSkill(self) and player.phase == Player.Start then
      return true
    elseif player ~= target and player:hasSkill(self) and target.phase == Player.Start then
      return not target:isKongcheng()
    end
  end,
  on_cost = function(self, event, target, player, data)
    if target == player then
      return true
    else
      local isYang = player:getSwitchSkillState(self.name) == fk.SwitchYang
      if not isYang then
        local cid = player.room:askForCard(target, 1, 1, false, self.name, true, ".|.|spade,club", "#wd_heg__juqi-black:"..player.id)
        if #cid > 0 then
          self.cost_data = cid
          return true
        end
      else
        local cid = player.room:askForCard(target, 1, 1, false, self.name, true, ".|.|heart,diamond", "#wd_heg__juqi-red:"..player.id)
        if #cid > 0 then
          self.cost_data = cid
          return true
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local isYang = player:getSwitchSkillState(self.name) == fk.SwitchYang
    if not isYang then
      if player == target then
        player:broadcastSkillInvoke(self.name, 1)
        player.room:notifySkillInvoked(player, self.name, "switch")
        player:drawCards(3, self.name)
      else
        player:broadcastSkillInvoke(self.name, 4)
        player.room:notifySkillInvoked(player, self.name, "switch")
        local cid = self.cost_data
        if #cid > 0 then
          target:showCards(cid)
          player.room:obtainCard(player, cid, true, fk.ReasonGive, target.id)
        end
      end
    else
      if player == target then
        player:broadcastSkillInvoke(self.name, 2)
        player.room:notifySkillInvoked(player, self.name, "switch")
        player.room:setPlayerMark(player, "@@wd_heg__juqi_buff-turn", 1)
      else
        player:broadcastSkillInvoke(self.name, 3)
        player.room:notifySkillInvoked(player, self.name, "switch")
        local cid = self.cost_data
        if #cid > 0 then
          target:showCards(cid)
          player.room:obtainCard(player, cid, true, fk.ReasonGive, target.id)
        end
      end
    end
  end,
  refresh_events = {fk.DamageCaused},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:getMark("@@wd_heg__juqi_buff-turn") > 0 and player:getMark("wd_heg__juqi_used-turn") == 0
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "wd_heg__juqi_used-turn", 1)
    data.damage = data.damage + 1
    return
  end,
}
local juqi_buff = fk.CreateTargetModSkill{
  name = "#wd_heg__juqi_buff",
  bypass_times = function(self, player, skill, scope, card, to)
    return card and player:getMark("@@wd_heg__juqi_buff-turn") > 0 and U.isPureCard(data.card)
  end,
}
juqi:addRelatedSkill(juqi_buff)
simayan:addSkill(juqi)
simayan:addCompanions("wd_heg__yangyan")
simayan:addCompanions("wd_heg__yangzhi")
simayan:addCompanions("wd_heg__yanghu")
simayan:addCompanions("wd_heg__duyu")
Fk:loadTranslationTable{
  ["wd_heg__simayan"] = "司马炎",
  ["#wd_heg__simayan"] = "晋武帝",
  ["illustrator:wd_heg__simayan"] = "鬼画府",

  ["wd_heg__juqi"] = "举棋",
  [":wd_heg__juqi"] = "转换技：①准备阶段，你摸三张牌/其他角色准备阶段，其可以展示并交给你一张黑色手牌；②准备阶段，令你本回合使用非转化非虚拟牌无次数限制且本回合首次造成的伤害+1/其他角色的准备阶段，"..
  "其可以展示并交给你一张红色手牌。",
  ["@@wd_heg__juqi_buff-turn"] = "举棋：加伤",
  ["#wd_heg__juqi-black"] = "举棋：你可以展示并交给 %src 一张黑色手牌",
  ["#wd_heg__juqi-red"] = "举棋：你可以展示并交给 %src 一张红色手牌",

  ["$wd_heg__juqi1"] = "事须从缓，养兵以待。",
  ["$wd_heg__juqi2"] = "即日伐吴，朕意已决。",
  ["$wd_heg__juqi3"] = "（交给牌）公闾之言字字珠玑，当养精蓄锐，以静制动。",
  ["$wd_heg__juqi4"] = "（交给牌）依元凯之疏，此时伐吴可显朕之威名，以定四海。",
  ["~wd_heg__simayan"] = "孝礼不彰，九鼎将崩......",
  ["$wd_heg__simayan_win_audio"] = "好戏才刚刚开始......",
}

return extension
